package com.baosight.risk.service.quartz.impl;

import com.baosight.risk.api.fltd.FltdProcessService;
import com.baosight.risk.api.quartz.ISysSyncOrgService;
import com.baosight.risk.api.xtzy.IXtzyCompanyService;
import com.baosight.risk.base.service.BaseServiceImpl;
import com.baosight.risk.common.annotation.Log;
import com.baosight.risk.common.aspects.factory.AsyncFactory;
import com.baosight.risk.common.bean.BeanUtils;
import com.baosight.risk.common.manager.AsyncManager;
import com.baosight.risk.common.utils.IDGenerator;
import com.baosight.risk.common.utils.ShiroUtils;
import com.baosight.risk.common.utils.StringUtils;
import com.baosight.risk.mapper.quartz.SysSyncOrgMapper;
import com.baosight.risk.service.quartz.entity.SyncOrgEntitiy;
import com.baosight.risk.service.system.entity.SysOperLog;
import com.baosight.risk.service.xtzy.entity.XtzyCompany;
import com.baosight.risk.service.xtzy.entity.XtzyOrgEhr;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @author CuiShihao
 * <p>
 * 定时任务 同步组织实现
 */
@Service
@Slf4j
public class SysSyncOrgServiceImpl implements ISysSyncOrgService {

    @Autowired
    private SysSyncOrgMapper sysSyncOrgMapper;

    @Autowired
    private FltdProcessService fltdProcessService;

    @Autowired
    private IXtzyCompanyService companyService;

    @Override
    public void batchInsertUserList(List<XtzyCompany> orgList) {
        sysSyncOrgMapper.batchInsertOrgList(orgList);
    }

    @Override
    public void getOrgFromOtherDB(String params, String jobId) throws Exception {
        List<SysOperLog> logs = new ArrayList<>();
        Exception error = null;
        try {
            List<XtzyCompany> resultList = new ArrayList<>();
            // 查找BGTA下全部公司
            List<String> initOrgCodeList = new ArrayList<String>(Arrays.asList("BGTA"));

            // 第二层级组织数据结果
            List<SyncOrgEntitiy> secondOrgList = sysSyncOrgMapper.getOrgFromOtherDB(initOrgCodeList);
            List<String> secondOrgCodeList = new ArrayList<>();
            for (SyncOrgEntitiy syncOrgEntitiy : secondOrgList) {
                XtzyCompany xtzyCompany = new XtzyCompany();
                xtzyCompany.setId(syncOrgEntitiy.getOrgCode());
                xtzyCompany.setCompCode(syncOrgEntitiy.getOrgCode());
                xtzyCompany.setCompName(syncOrgEntitiy.getOrgName());
                xtzyCompany.setCompNameS(syncOrgEntitiy.getOrgName());
                xtzyCompany.setCompNameL(syncOrgEntitiy.getOrgName());
                xtzyCompany.setParentGuid(syncOrgEntitiy.getTargetOrgCode());
                xtzyCompany.setEndLevelFlag((short) 0);
                xtzyCompany.setPathLevel((short) 2);
                xtzyCompany.setPathCode("/BGTA/" + syncOrgEntitiy.getOrgCode());
                xtzyCompany.setPathName("/宝山钢铁股份有限公司/" + syncOrgEntitiy.getOrgName());
                xtzyCompany.setCompType("1");
                xtzyCompany.setCompTypeName("公司");
                xtzyCompany.setStatus("10");
                xtzyCompany.setParentName(syncOrgEntitiy.getTargetOrgName());
                resultList.add(xtzyCompany);
                secondOrgCodeList.add(syncOrgEntitiy.getOrgCode());
            }

            // 处理第三层级组织数据结果
            if (secondOrgCodeList.size() != 0) {
                List<SyncOrgEntitiy> thirdOrgList = sysSyncOrgMapper.getOrgFromOtherDB(secondOrgCodeList);
                for (SyncOrgEntitiy syncOrgEntitiy : thirdOrgList) {
                    XtzyCompany xtzyCompany = new XtzyCompany();
                    xtzyCompany.setId(syncOrgEntitiy.getOrgCode());
                    xtzyCompany.setCompCode(syncOrgEntitiy.getOrgCode());
                    xtzyCompany.setCompName(syncOrgEntitiy.getOrgName());
                    xtzyCompany.setCompNameS(syncOrgEntitiy.getOrgName());
                    xtzyCompany.setCompNameL(syncOrgEntitiy.getOrgName());
                    xtzyCompany.setParentGuid(syncOrgEntitiy.getTargetOrgCode());
                    xtzyCompany.setEndLevelFlag((short) 0);
                    xtzyCompany.setPathLevel((short) 3);
                    xtzyCompany.setPathCode("/BGTA/" + syncOrgEntitiy.getTargetOrgCode() + "/" + syncOrgEntitiy.getOrgCode());
                    xtzyCompany.setPathName("/宝山钢铁股份有限公司/" + syncOrgEntitiy.getTargetOrgName() + "/" + syncOrgEntitiy.getOrgName());
                    xtzyCompany.setCompType("1");
                    xtzyCompany.setCompTypeName("公司");
                    xtzyCompany.setStatus("10");
                    xtzyCompany.setParentName(syncOrgEntitiy.getTargetOrgName());
                    resultList.add(xtzyCompany);
                }
            }
            if (!resultList.isEmpty()) {
                batchInsertUserList(resultList);
            }
            logs.add(fltdProcessService.getLog("同步组织定时任务执行成功", 0, "", jobId));
        }catch (Exception e) {
            error = e;
            logs.add(fltdProcessService.getLog("同步组织定时任务执行失败", 1, e.getMessage(), jobId));
        }
        // 保存日志到数据库
        AsyncManager.me().execute(AsyncFactory.batchRecordOper(logs));
        if (error != null) {
            throw error;
        }
    }

    @Override
    public void doUpgradeOrg(String params, String jobId) throws Exception {
        List<SysOperLog> logs = new ArrayList<>();
        Exception error = null;
        try {
            // ehr的组织结构树
            Map<String, Object> orgTree = companyService.selectOrgTree("2");

            // 风控系统的组织列表
            List<XtzyCompany> xtzyCompanies = companyService.selectAllCompany(new XtzyCompany());
            Map<String, XtzyCompany> xtzyCompanyMap = new HashMap<>();
            for (XtzyCompany xtzyCompany : xtzyCompanies) {
                xtzyCompanyMap.put(xtzyCompany.getCompCode(), xtzyCompany);
            }

            // 同步组织
            contrast(orgTree, xtzyCompanyMap);

            logs.add(fltdProcessService.getLog("同步组织定时任务执行成功", 0, "", jobId));
        } catch (Exception e) {
            error = e;
            logs.add(fltdProcessService.getLog("同步组织定时任务执行失败", 1, e.getMessage(), jobId));
        }
        // 保存日志到数据库
        AsyncManager.me().execute(AsyncFactory.batchRecordOper(logs));
        if (error != null) {
            throw error;
        }
    }

    private void contrast(Map<String, Object> orgTree, Map<String, XtzyCompany> xtzyCompanyMap) throws Exception {
        List<Map<String, Object>> childList = (List<Map<String, Object>>) orgTree.get("children");
        for (Map<String, Object> childMap : childList) {
            String orgCode = (String) childMap.get("orgCode");
            String orgName = (String) childMap.get("orgName");
            String targetOrgCode = (String) childMap.get("targetOrgCode");
            String targetOrgName = (String) childMap.get("targetOrgName");

            XtzyCompany xtzyCompany = xtzyCompanyMap.get(orgCode);
            if (xtzyCompany == null) {
                // 风控系统中缺少对应的组织，需要新增
                XtzyCompany newCompany = (XtzyCompany) BeanUtils.initBean(new XtzyCompany());
                newCompany.setId(orgCode);
                newCompany.setCompCode(orgCode);
                newCompany.setCompName(orgName);
                newCompany.setCompNameS(orgName);
                newCompany.setCompNameL(flterSymbol((String) childMap.get("orgFullName")));
                newCompany.setParentGuid(targetOrgCode);
                newCompany.setParentName(targetOrgName);
                newCompany.setEndLevelFlag((short) 1);
                newCompany.setPathLevel(Short.valueOf("" + childMap.get("pathLevel")));
                newCompany.setPathCode(flterSymbol((String) childMap.get("pathCode")));
                newCompany.setPathName(flterSymbol((String) childMap.get("pathName")));
                newCompany.setCompType(convertCompType((String) childMap.get("orgTypeId")));
                newCompany.setCompTypeName((String) childMap.get("orgType"));
                newCompany.setStatus("10");
                newCompany.setRowOrder(generateRowOrder(xtzyCompanyMap, targetOrgCode));
                newCompany.setRiskFlag("N");

                XtzyCompany parentCompany = xtzyCompanyMap.get(orgTree.get("orgCode"));
                newCompany.setDepartmentClass(parentCompany.getDepartmentClass());
                newCompany.setDepartmentClassName(parentCompany.getDepartmentClassName());
                xtzyCompanyMap.put(orgCode, newCompany);
                companyService.insert(newCompany);
            } else {
                // 已存在相同组织，则修改部分字段
                XtzyCompany updateCompany = new XtzyCompany();
                updateCompany.setId(xtzyCompany.getId());
                updateCompany.setCompNameS(orgName);
                updateCompany.setCompNameL(flterSymbol((String) childMap.get("orgFullName")));
                updateCompany.setCompType(convertCompType((String) childMap.get("orgTypeId")));
                updateCompany.setCompTypeName((String) childMap.get("orgType"));
                updateCompany.setUpdateBy("admin");
                updateCompany.setUpdateTime(new Date());
                companyService.update(updateCompany);
            }
        }
    }

    /**
     * 转换路径符号
     */
    private String flterSymbol(String str) {
        StringBuffer sb = new StringBuffer();
        sb.append("/").append(str.replaceAll("\\\\", "/"));
        if(str.endsWith("\\")) {
            return sb.substring(0, sb.length()-1);
        }
        return sb.toString();
    }

    /**
     * 转换组织类型(ehr->risk)
     *
     */
    private String convertCompType(String ehrType) {
        String type = "";
        switch (ehrType) {
            case "1":
                type = "4";
                break;
            case "8":
                type = "1";
                break;
            default:
                break;
        }
        return type;
    }

    /**
     * 生成新的排序字段，如果同级下没有节点则加上001，否则同级节点排序最大值+1
     *
     */
    private String generateRowOrder(Map<String, XtzyCompany> xtzyCompanyMap, String parentCode) throws Exception {
        String rowOrder = "";
        for (String companyCode : xtzyCompanyMap.keySet()) {
            XtzyCompany xtzyCompany = xtzyCompanyMap.get(companyCode);
            if (parentCode.equals(xtzyCompany.getParentGuid())) {
                if(xtzyCompany.getRowOrder().compareTo(rowOrder) > 0) {
                    rowOrder = xtzyCompany.getRowOrder();
                }
            }
        }
        if (StringUtils.isEmpty(rowOrder)) {
            return xtzyCompanyMap.get(parentCode).getRowOrder() + "001";
        }else {
            return String.valueOf(Long.valueOf(rowOrder) + 1);
        }
    }

}
